#!/bin/sh

set -eu

AIRCONNECT_USER="$(echo "${SYNOPKG_PKGNAME}" | awk '{print tolower($_)}')"
CONFIG_UPNP_FILE="config.xml"
CONFIG_UPNP_DESTINATION="${SYNOPKG_PKGDEST}/${CONFIG_UPNP_FILE}"
CONFIG_CAST_FILE="config-cast.xml"
CONFIG_CAST_DESTINATION="${SYNOPKG_PKGDEST}/${CONFIG_CAST_FILE}"
AIRCONNECT_DESTINATION="${SYNOPKG_PKGDEST_VOL}/airconnect"
AIRCONNECT_CONFIG_FILE="airconnect.conf"
AIRCONNECT_CONFIG="${SYNOPKG_PKGDEST}/${AIRCONNECT_CONFIG_FILE}"

LOG="${SYNOPKG_PKGDEST}/log/${AIRCONNECT_USER}.log"
LOGBACKUP="${SYNOPKG_PKGDEST}/log/${AIRCONNECT_USER}.1.log"

# backward compatibility for older packages, airconnect configuration file is needed
if [ ! -f "${AIRCONNECT_CONFIG}" ]; then
    echo "[$(date +'%T')] AirConnect config file does not exist! Please uninstall the package and reinstall it again!" >>"$LOG"
    echo "[$(date +'%T')] AirConnect config file does not exist! Please uninstall the package and reinstall it again!" >>"$SYNOPKG_TEMP_LOGFILE"
    exit 150
fi

# import config file
# shellcheck source=/dev/null
. "${AIRCONNECT_CONFIG}"

# pgrep not available by default on synology devices
# shellcheck disable=SC2009
get_pid() {
    PID=$(ps aux | grep -E 'airupnp|aircast' | grep -v grep | awk '{print $2}')
}

start_airconnect_on_ip() {
    # Cleanup before doing anything
    # check if a logfile backup was already created before, delete it on the second start
    if [ -f "${LOGBACKUP}" ]; then
        [ "$(stat --printf '%s' "${LOGBACKUP}")" -gt 52428800 ] && rm "${LOGBACKUP}"
    fi
    # check if logfile is greater than 50mb, if yes delete it before starting airconnect
    if [ -f "${LOG}" ]; then
        [ "$(stat --printf '%s' "${LOG}")" -gt 52428800 ] && cp -p "${LOG}" "${LOGBACKUP}" && rm "${LOG}"
    fi
    echo "[$(date +'%T')] Linking airconnect configuration to \"${AIRCONNECT_DESTINATION}/${AIRCONNECT_CONFIG_FILE}\"." >>"$LOG"

    ln -fs "${AIRCONNECT_CONFIG}" "${AIRCONNECT_DESTINATION}/${AIRCONNECT_CONFIG_FILE}"

    if [ "${AIRUPNP_ENABLED}" = 1 ] && [ "${AIRCAST_ENABLED}" = 1 ]; then
        if [ -n "${AIRUPNP_PORT}" ]; then
            if netstat -tln | grep :"${AIRUPNP_PORT}"; then
                echo "[$(date +'%T')] Your selected port ${AIRUPNP_PORT} is already in use." >>"$LOG"
                echo "[$(date +'%T')] Please check what is running on the port and try again." >>"$LOG"
                echo "[$(date +'%T')] Port ${AIRUPNP_PORT} already in use. Please check what is running on the port and try again." >>"$SYNOPKG_TEMP_LOGFILE"
                return 1
            fi
        else
            echo "[$(date +'%T')] AIRUPNP port cannot be found! Please uninstall the package and reinstall it again (or set AIRUPNP_PORT in \"${AIRCONNECT_CONFIG}\")!" >>"$LOG"
            echo "[$(date +'%T')] AIRUPNP port cannot be found! Please uninstall the package and reinstall it again (or set AIRUPNP_PORT in \"${AIRCONNECT_CONFIG}\")!" >>"$SYNOPKG_TEMP_LOGFILE"
            exit 150
        fi

        if [ -z "${AIRUPNP_LOGLEVEL}" ] || [ -z "${AIRCAST_LOGLEVEL}" ]; then
            echo "[$(date +'%T')] Loglevel for AIRUPNP and AIRCAST cannot be found! Please uninstall the package and reinstall it again (or set AIRCAST_LOGLEVEL and AIRUPNP_LOGLEVEL in \"${AIRCONNECT_CONFIG}\")!" >>"$LOG"
            echo "[$(date +'%T')] Loglevel for AIRUPNP and AIRCAST cannot be found! Please uninstall the package and reinstall it again (or set AIRCAST_LOGLEVEL and AIRUPNP_LOGLEVEL in \"${AIRCONNECT_CONFIG}\")!" >>"$SYNOPKG_TEMP_LOGFILE"
            exit 150
        fi

        echo "[$(date +'%T')] Linking airupnp configuration to \"${AIRCONNECT_DESTINATION}/${CONFIG_UPNP_FILE}\"." >>"$LOG"
        ln -fs "${AIRCONNECT_DESTINATION}/${CONFIG_UPNP_FILE}" "${CONFIG_UPNP_DESTINATION}"
        echo "[$(date +'%T')] Starting airupnp on ${SYNO_IP}:${AIRUPNP_PORT}" >>"$LOG"
        if [ -n "${FILTER_AIRPLAY2_DEVICES}" ] && [ -n "${AIRUPNP_LATENCY}" ]; then
            "${SYNOPKG_PKGDEST}"/airupnp -b "${SYNO_IP}":"${AIRUPNP_PORT}" -g "${AIRUPNP_CONTENTLENGTH_MODE}" -l "${AIRUPNP_LATENCY}" -x "${CONFIG_UPNP_DESTINATION}" -o "${FILTER_AIRPLAY2_DEVICES}" -z -f "${LOG}" -d "${AIRUPNP_LOGLEVEL}" 2>&1
        elif [ -n "${FILTER_AIRPLAY2_DEVICES}" ]; then
            "${SYNOPKG_PKGDEST}"/airupnp -b "${SYNO_IP}":"${AIRUPNP_PORT}" -g "${AIRUPNP_CONTENTLENGTH_MODE}" -x "${CONFIG_UPNP_DESTINATION}" -o "${FILTER_AIRPLAY2_DEVICES}" -z -f "${LOG}" -d "${AIRUPNP_LOGLEVEL}" 2>&1
        elif [ -n "${AIRUPNP_LATENCY}" ]; then
            "${SYNOPKG_PKGDEST}"/airupnp -b "${SYNO_IP}":"${AIRUPNP_PORT}" -g "${AIRUPNP_CONTENTLENGTH_MODE}" -l "${AIRUPNP_LATENCY}" -x "${CONFIG_UPNP_DESTINATION}" -z -f "${LOG}" -d "${AIRUPNP_LOGLEVEL}" 2>&1
        else
            "${SYNOPKG_PKGDEST}"/airupnp -b "${SYNO_IP}":"${AIRUPNP_PORT}" -g "${AIRUPNP_CONTENTLENGTH_MODE}" -x "${CONFIG_UPNP_DESTINATION}" -z -f "${LOG}" -d "${AIRUPNP_LOGLEVEL}" 2>&1
        fi
        echo "[$(date +'%T')] Linking aircast configuration to \"${AIRCONNECT_DESTINATION}/${CONFIG_CAST_FILE}\"." >>"$LOG"
        ln -fs "${AIRCONNECT_DESTINATION}/${CONFIG_CAST_FILE}" "${CONFIG_CAST_DESTINATION}"
        echo "[$(date +'%T')] Starting aircast on ${SYNO_IP}" >>"$LOG"
        if [ -n "${AIRCAST_LATENCY}" ]; then
            "${SYNOPKG_PKGDEST}"/aircast -b "${SYNO_IP}" -l "${AIRCAST_LATENCY}" -x "${CONFIG_CAST_DESTINATION}" -z -f "${LOG}" -d "${AIRCAST_LOGLEVEL}" 2>&1
        else
            "${SYNOPKG_PKGDEST}"/aircast -b "${SYNO_IP}" -x "${CONFIG_CAST_DESTINATION}" -z -f "${LOG}" -d "${AIRCAST_LOGLEVEL}" 2>&1
        fi
    elif [ "${AIRUPNP_ENABLED}" = 1 ]; then
        if [ -n "${AIRUPNP_PORT}" ]; then
            if netstat -tln | grep :"${AIRUPNP_PORT}"; then
                echo "[$(date +'%T')] Your selected port ${AIRUPNP_PORT} is already in use." >>"$LOG"
                echo "[$(date +'%T')] Please check what is running on the port and try again." >>"$LOG"
                echo "[$(date +'%T')] Port ${AIRUPNP_PORT} already in use. Please check what is running on the port and try again." >>"$SYNOPKG_TEMP_LOGFILE"
                return 1
            fi
        else
            echo "[$(date +'%T')] AIRUPNP port cannot be found! Please uninstall the package and reinstall it again (or set AIRUPNP_PORT in \"${AIRCONNECT_CONFIG}\")!" >>"$LOG"
            echo "[$(date +'%T')] AIRUPNP port cannot be found! Please uninstall the package and reinstall it again (or set AIRUPNP_PORT in \"${AIRCONNECT_CONFIG}\")!" >>"$SYNOPKG_TEMP_LOGFILE"
            exit 150
        fi

        if [ -z "${AIRUPNP_LOGLEVEL}" ]; then
            echo "[$(date +'%T')] Loglevel for AIRUPNP cannot be found! Please uninstall the package and reinstall it again (or set AIRUPNP_LOGLEVEL in \"${AIRCONNECT_CONFIG}\")!" >>"$LOG"
            echo "[$(date +'%T')] Loglevel for AIRUPNP cannot be found! Please uninstall the package and reinstall it again (or set AIRUPNP_LOGLEVEL in \"${AIRCONNECT_CONFIG}\")!" >>"$SYNOPKG_TEMP_LOGFILE"
            exit 150
        fi

        echo "[$(date +'%T')] Linking airupnp configuration to \"${AIRCONNECT_DESTINATION}/${CONFIG_UPNP_FILE}\"." >>"$LOG"
        ln -fs "${AIRCONNECT_DESTINATION}/${CONFIG_UPNP_FILE}" "${CONFIG_UPNP_DESTINATION}"
        echo "[$(date +'%T')] Starting airupnp on ${SYNO_IP}:${AIRUPNP_PORT}" >>"$LOG"
        if [ -n "${FILTER_AIRPLAY2_DEVICES}" ] && [ -n "${AIRUPNP_LATENCY}" ]; then
            "${SYNOPKG_PKGDEST}"/airupnp -b "${SYNO_IP}":"${AIRUPNP_PORT}" -g "${AIRUPNP_CONTENTLENGTH_MODE}" -l "${AIRUPNP_LATENCY}" -x "${CONFIG_UPNP_DESTINATION}" -o "${FILTER_AIRPLAY2_DEVICES}" -z -f "${LOG}" -d "${AIRUPNP_LOGLEVEL}" 2>&1
        elif [ -n "${FILTER_AIRPLAY2_DEVICES}" ]; then
            "${SYNOPKG_PKGDEST}"/airupnp -b "${SYNO_IP}":"${AIRUPNP_PORT}" -g "${AIRUPNP_CONTENTLENGTH_MODE}" -x "${CONFIG_UPNP_DESTINATION}" -o "${FILTER_AIRPLAY2_DEVICES}" -z -f "${LOG}" -d "${AIRUPNP_LOGLEVEL}" 2>&1
        elif [ -n "${AIRUPNP_LATENCY}" ]; then
            "${SYNOPKG_PKGDEST}"/airupnp -b "${SYNO_IP}":"${AIRUPNP_PORT}" -g "${AIRUPNP_CONTENTLENGTH_MODE}" -l "${AIRUPNP_LATENCY}" -x "${CONFIG_UPNP_DESTINATION}" -z -f "${LOG}" -d "${AIRUPNP_LOGLEVEL}" 2>&1
        else
            "${SYNOPKG_PKGDEST}"/airupnp -b "${SYNO_IP}":"${AIRUPNP_PORT}" -g "${AIRUPNP_CONTENTLENGTH_MODE}" -x "${CONFIG_UPNP_DESTINATION}" -z -f "${LOG}" -d "${AIRUPNP_LOGLEVEL}" 2>&1
        fi
    elif [ "${AIRCAST_ENABLED}" = 1 ]; then
        if [ -z "${AIRCAST_LOGLEVEL}" ]; then
            echo "[$(date +'%T')] Loglevel for AIRCAST cannot be found! Please uninstall the package and reinstall it again (or set AIRCAST_LOGLEVEL in \"${AIRCONNECT_CONFIG}\")!" >>"$LOG"
            echo "[$(date +'%T')] Loglevel for AIRCAST cannot be found! Please uninstall the package and reinstall it again (or set AIRCAST_LOGLEVEL in \"${AIRCONNECT_CONFIG}\")!" >>"$SYNOPKG_TEMP_LOGFILE"
            exit 150
        fi

        echo "[$(date +'%T')] Linking aircast configuration to \"${AIRCONNECT_DESTINATION}/${CONFIG_CAST_FILE}\"." >>"$LOG"
        ln -fs "${AIRCONNECT_DESTINATION}/${CONFIG_CAST_FILE}" "${CONFIG_CAST_DESTINATION}"
        echo "[$(date +'%T')] Starting aircast on ${SYNO_IP}" >>"$LOG"
        if [ -n "${AIRCAST_LATENCY}" ]; then
            "${SYNOPKG_PKGDEST}"/aircast -b "${SYNO_IP}" -l "${AIRCAST_LATENCY}" -x "${CONFIG_CAST_DESTINATION}" -z -f "${LOG}" -d "${AIRCAST_LOGLEVEL}" 2>&1
        else
            "${SYNOPKG_PKGDEST}"/aircast -b "${SYNO_IP}" -x "${CONFIG_CAST_DESTINATION}" -z -f "${LOG}" -d "${AIRCAST_LOGLEVEL}" 2>&1
        fi
    else
        echo "[$(date +'%T')] Neither airupnp nor aircast should be launched! Please uninstall the package and reinstall it again (or set AIRUPNP_ENABLED=1 and/or AIRCAST_ENABLED=1 in \"${AIRCONNECT_CONFIG}\")!" >>"$LOG"
        echo "[$(date +'%T')] Neither airupnp nor aircast should be launched! Please uninstall the package and reinstall it again (or set AIRUPNP_ENABLED=1 and/or AIRCAST_ENABLED=1 in \"${AIRCONNECT_CONFIG}\")!" >>"$SYNOPKG_TEMP_LOGFILE"
        return 150
    fi
    return 0
}

start_airconnect() {
    if [ -n "${SYNO_IP}" ]; then
        if start_airconnect_on_ip; then
            echo "[$(date +'%T')] AirConnect successfully started on ip \"${SYNO_IP}\"!" >>"$LOG"
            return 0
        else
            echo "[$(date +'%T')] Failed to start AirConnect on ip \"${SYNO_IP}\", stopping it..." >>"$LOG"
            echo "[$(date +'%T')] Failed to start AirConnect on ip \"${SYNO_IP}\", stopping it..." >>"$SYNOPKG_TEMP_LOGFILE"
            stop_airconnect
        fi
    else
        echo "[$(date +'%T')] Synology IP cannot be found! Please uninstall the package and reinstall it again (or change SYNO_IP in \"${AIRCONNECT_CONFIG}\")!" >>"$LOG"
        echo "[$(date +'%T')] Synology IP cannot be found! Please uninstall the package and reinstall it again! (or change SYNO_IP in \"${AIRCONNECT_CONFIG}\")" >>"$SYNOPKG_TEMP_LOGFILE"
        exit 150
    fi
}

stop_airconnect() {
    get_pid
    if [ -n "${PID}" ]; then
        # shellcheck disable=SC2086
        kill $PID
    else
        return 0
    fi
    sleep 10

    if [ "${AIRUPNP_ENABLED}" = 1 ] && [ "${AIRCAST_ENABLED}" = 1 ]; then
        # pgrep not available by default on synology devices
        # shellcheck disable=SC2009
        if ! ps | grep -E 'airupnp' | grep -v -q grep && ! ps | grep -E 'aircast' | grep -v -q grep; then
            return 0
        elif ps | grep -E 'airupnp' | grep -v -q grep && ps | grep -E 'aircast' | grep -v -q grep; then
            echo "[$(date +'%T')] Stop: airupnp & aircast are still running!" >>"$LOG"
            echo "[$(date +'%T')] Stop: airupnp & aircast are still running" >>"$SYNOPKG_TEMP_LOGFILE"
            return 1
        elif ! ps | grep -E 'airupnp' | grep -v -q grep && ps | grep -E 'aircast' | grep -v -q grep; then
            echo "[$(date +'%T')] Stop: aircast is still running!" >>"$LOG"
            echo "[$(date +'%T')] Stop: aircast is still running!" >>"$SYNOPKG_TEMP_LOGFILE"
            return 1
        elif ps | grep -E 'airupnp' | grep -v -q grep && ! ps | grep -E 'aircast' | grep -v -q grep; then
            echo "[$(date +'%T')] Stop: airupnp is still running!" >>"$LOG"
            echo "[$(date +'%T')] Stop: airupnp is still running!" >>"$SYNOPKG_TEMP_LOGFILE"
            return 1
        fi
    elif [ "${AIRUPNP_ENABLED}" = 1 ]; then
        # pgrep not available by default on synology devices
        # shellcheck disable=SC2009
        if ! ps | grep -E 'airupnp' | grep -v -q grep; then
            return 0
        else
            echo "[$(date +'%T')] Stop: airupnp is still running!" >>"$LOG"
            echo "[$(date +'%T')] Stop: airupnp is still running!" >>"$SYNOPKG_TEMP_LOGFILE"
            return 1
        fi
    elif [ "${AIRCAST_ENABLED}" = 1 ]; then
        # pgrep not available by default on synology devices
        # shellcheck disable=SC2009
        if ! ps | grep -E 'aircast' | grep -v -q grep; then
            return 0
        else
            echo "[$(date +'%T')] Stop: aircast is still running!" >>"$LOG"
            echo "[$(date +'%T')] Stop: aircast is still running!" >>"$SYNOPKG_TEMP_LOGFILE"
            return 1
        fi
    fi
    return 1
}

airconnect_status() {
    if [ "${AIRUPNP_ENABLED}" = 1 ] && [ "${AIRCAST_ENABLED}" = 1 ]; then
        # pgrep not available by default on synology devices
        # shellcheck disable=SC2009
        if ps | grep -E 'airupnp' | grep -v -q grep && ps | grep -E 'aircast' | grep -v -q grep; then
            return 0
        elif ! ps | grep -E 'airupnp' | grep -v -q grep && ! ps | grep -E 'aircast' | grep -v -q grep; then
            return 3
        elif ! ps | grep -E 'airupnp' | grep -v -q grep && ps | grep -E 'aircast' | grep -v -q grep; then
            echo "[$(date +'%T')] Status: airupnp not running!" >>"$LOG"
            return 3
        elif ps | grep -E 'airupnp' | grep -v -q grep && ! ps | grep -E 'aircast' | grep -v -q grep; then
            echo "[$(date +'%T')] Status: aircast not running!" >>"$LOG"
            return 3
        else
            return 4
        fi
    elif [ "${AIRUPNP_ENABLED}" = 1 ]; then
        # pgrep not available by default on synology devices
        # shellcheck disable=SC2009
        if ps | grep -E 'airupnp' | grep -v -q grep; then
            return 0
        else
            echo "[$(date +'%T')] Status: airupnp not running!" >>"$LOG"
            return 3
        fi
    elif [ "${AIRCAST_ENABLED}" = 1 ]; then
        # pgrep not available by default on synology devices
        # shellcheck disable=SC2009
        if ps | grep -E 'aircast' | grep -v -q grep; then
            return 0
        else
            echo "[$(date +'%T')] Status: aircast not running!" >>"$LOG"
            return 3
        fi
    fi
    # return unknown if nothing matched
    return 4
}

case $1 in
start)
    echo "[$(date +'%T')] Starting AirConnect ..." >>"$LOG"
    start_airconnect
    exit $?
    ;;
stop)
    echo "[$(date +'%T')] Stopping AirConnect ..." >>"$LOG"
    stop_airconnect
    exit $?
    ;;
status)
    if airconnect_status; then
        echo "[$(date +'%T')] AirConnect is running"
        exit 0
    else
        echo "[$(date +'%T')] AirConnect is not running"
        exit 3
    fi
    ;;
log)
    echo "${LOG}"
    exit 0
    ;;
*)
    exit 1
    ;;
esac
